﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using PickGold;
using PickGold.Api;
using PickGold.Base;
using PickGold.Collections;

using BaseCommon = PickGold.Base.Common;

namespace PickGold.Base.OCR
{
	[Serializable]
	[ComVisible(true)]
	[ClassInterface(ClassInterfaceType.AutoDispatch)]
	public class MatchModel
	{
		public string Text;
		public int Serial;
		public long Frequency;
		public Font TextFont;
		public bool[,] TextPixels;
		[NonSerialized]
		public byte[] TextBuffer;
		[NonSerialized]
		public string TextB64;
		[NonSerialized]
		public string TextAscii;
		[NonSerialized]
		public int Matched;
		[NonSerialized]
		public int MatchTotal;

		public static byte[] GetBuffer(bool[,] pixels)
		{
			var i = 0;
			var ls = new List<byte>();
			var xx = pixels.GetLength(0);
			var yy = pixels.GetLength(1);
			for (var x = 0; x < xx; x++)
			{
				for (var y = 0; y < yy; y++)
				{
					if (i / 8 >= ls.Count)
						ls.Add(BitUtil.B08_ZERO);
					if (pixels[x, y])
						ls[i / 8] = (byte)(ls[i / 8] | BitUtil.B08_2Pow(i % 8));
					i++;
				}
				if (yy % 8 != 0)
					i = i + 8 - yy % 8;
			}
			return ls.ToArray();
		}

		public static string GetB64(byte[] buffer)
		{
			return Convert.ToBase64String(buffer);
		}

		public static string GetAscii(byte[] buffer)
		{
			return Encoding.ASCII.GetString(buffer);
		}

		public override bool Equals(object obj)
		{
			var mm = obj as MatchModel;
			if (mm == null)
				return base.Equals(obj);

			if (this.TextAscii == mm.TextAscii && this.TextB64 == mm.TextB64)
				return true;

			return false;
		}

		public override int GetHashCode()
		{
			if (this.TextPixels == null)
				return base.GetHashCode();

			return this.TextPixels.GetHashCode();
		}

		public override string ToString()
		{
			//return base.ToString();
			if (this.TextPixels == null)
				return string.Empty;

			if (string.IsNullOrEmpty(this.Text))
				return "¶ = " + this.TextB64;

			return this.Text + " = " + this.TextB64;
		}
	}
}
